<?php
/*
	Copyright (C) 2008 - 2012 Inanta Martsanto
	Inanta Martsanto (inanta@inationsoft.com)

	This file is part of NewStep Framework.

	NewStep Framework is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	NewStep Framework is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with NewStep Framework.  If not, see <http://www.gnu.org/licenses/>.
*/

namespace Inationsoft\NS;

use Inationsoft\NS\Core\Config;

/**
 *Handle function to manipulate number
 *
 *@author Inanta Martsanto <inanta@inationsoft.com>
 */
class Number extends Object {
	const FORMAT_MONEY = 1;
	const FORMAT_MONEY_WITH_CODE = 2;
	const FORMAT_MONEY_WITH_SYMBOL = 2;

	private static $_locale = null;

	static function format($value, $format) {
		self::loadLocale();

		switch($format) {
			case self::FORMAT_MONEY:
			case self::FORMAT_MONEY_WITH_CODE:
			case self::FORMAT_MONEY_WITH_SYMBOL:
				return (($format == self::FORMAT_MONEY ? '' : ($format == self::FORMAT_MONEY_WITH_SYMBOL ? self::$_locale['CurrencySymbol'] . ' ' : self::$_locale['CurrencyCode'] . ' ')) . number_format($value, self::$_locale['MoneyFractionDigit'], self::$_locale['MoneyDecimalPoint'], self::$_locale['MoneyThousandSeparator']));
		}
	}
	/**
	*Convert number from Roman numerals
	*
	*/
	static function fromRoman($number) {
		$result = 0;
		$romans = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400, 'C' => 100, 'XC' => 90,
			'L' => 50, 'XL' => 40, 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1,
		);

		if(!preg_match('/^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/', $number)) return $result;

		foreach ($romans as $key => $value) {
		    while (strpos($number, $key) === 0) {
			    $result += $value;
			    $number = substr($number, strlen($key));
		    }
		}

		return $result;
	}

	/**
	*Convert number to Roman numerals
	*
	*/
	static function toRoman($number) {
		$n = $number;
		$result = '';
		$romans = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400, 'C' => 100, 'XC' => 90,
			'L' => 50, 'XL' => 40, 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1,
		);

		foreach ($romans as $roman => $number) {
		    $matches = $n / $number;
		    $result .= str_repeat($roman, $matches);
		    $n = $n % $number;
		}
	    
		return $result;
	}
	
	private static function loadLocale() {
		if(self::$_locale == null) {
			require(NS_SYSTEM_PATH . '/' . Config::getInstance()->ConfigFolder . '/Locale.inc.php');
			self::$_locale = $Locale;
		}
	}
}
?>